class CListNode {
public:
    CListNode() : prev(nullptr), next(nullptr), key(0), val(0){}
    CListNode(int _key, int _val) : prev(nullptr), next(nullptr),key(_key), val(_val){}
public:
    int key;
    int val;
    CListNode *prev;
    CListNode *next;
};

class LRUCache {
public:
    CListNode *head;
    CListNode *tail;
    int size;
    int capacity;
    unordered_map<int, CListNode*> book;
public:
    LRUCache(int capacity) : size(0), capacity(0) {
        head = new CListNode();
        tail = new CListNode();
        head->next = tail;
        tail->prev = head;
        this->capacity = capacity;
    }
    
    int get(int key) {
        int result = book.find(key) == book.end() ? -1 : book[key]->val; 
        if (result != -1) 
            moveToHead(book[key]);
        return result;
    }
    
    void put(int key, int value) {
        if (book.find(key) == book.end()) {
            if (size == capacity) popTail();
            else size++;
            CListNode *node = new CListNode(key, value);
            book[key] = node;
            addToHead(node);
        } else {
            moveToHead(book[key]);
            book[key]->val = value;
        }
    }

    void moveToHead(CListNode *node) {
        if (node == nullptr) return;
        node->prev->next = node->next;
        node->next->prev = node->prev;
        node->prev = head;
        node->next = head->next;
        head->next->prev = node;
        head->next = node;
    }

    void popTail() {
        if (size == 0) return;
        CListNode *popNode = tail->prev;
        popNode->prev->next = tail;
        tail->prev = popNode->prev;
        book.erase(popNode->key);
        delete popNode;
    }

    void addToHead(CListNode *node) {
        node->prev = head;
        node->next = head->next;
        head->next->prev = node;
        head->next = node;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
